package com.server.llh.llhserverwork.activity.food;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;

import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.BaseFragment;
import com.server.llh.llhserverwork.adapter.FoodOrderInfoHolder;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.FoodOrderInfosBean;
import com.server.llh.llhserverwork.port.FoodOrderInfosInterface;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.TimeUtil;
import com.server.llh.llhserverwork.utils.ToastTool;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by ZTF on 2017-06-14.
 */

public class LlhFoodOrderAllFragment extends BaseFragment implements FoodOrderInfosInterface {
    private static final String TAG = "FoodOrderPay";
    private static final String FRAGMENT_INDEX = "fragment_index";
    @BindView(R.id.fragment_listview)
    ListView fragmentListview;
    SwipeRefreshLayout swipeRefreshLayout;
    Unbinder unbinder;
    private String muserId, mToken;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;
    private final int FIRST_FRAGMENT = 0;
    private final int SECOND_FRAGMENT = 1;
    private final int THREE_FRAGMENT = 2;
    private final int FOUR_FRAGMENT = 3;

    public static LlhFoodOrderAllFragment newInstance(int index) {
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_INDEX, index);
        LlhFoodOrderAllFragment fragment = new LlhFoodOrderAllFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    View rootView;
    private int mCurIndex = -1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        muserId = SharedPreferenceUtil.getUserInfo("customerId", getActivity().getApplicationContext());
        mToken = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getActivity().getApplicationContext());
        Log.d(TAG, "muserId=====" + muserId + "mToken==" + mToken);
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            Bundle bundle = getArguments();
            if (bundle != null) {
                mCurIndex = bundle.getInt(FRAGMENT_INDEX);
            }
            isPrepared = true;
            lazyLoad();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        unbinder = ButterKnife.bind(this, rootView);
        swipeRefreshLayout = (SwipeRefreshLayout) this.rootView.findViewById(R.id.refrash_data);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onRefreshReq();
            }
        });
        return rootView;
    }

    private void onRefreshReq() {
        if (mHasLoadedOnce == false || isPrepared == false || mHasLoadedOnce) {
            mHasLoadedOnce = true;
            isPrepared = true;
            mHasLoadedOnce = false;
        }
        lazyLoad();
    }

    @Override
    public void onResume() {
        onRefreshReq();
        super.onResume();
    }
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date curDate = new Date(System.currentTimeMillis());
    String str = formatter.format(curDate);
    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        switch (mCurIndex) {
            case FIRST_FRAGMENT:
                getOrderInfos(muserId, TimeUtil.setTimeDatas(str,1), str, "", "");
                break;
            case SECOND_FRAGMENT:
                getOrderInfos(muserId, "", "", "", "");
                break;
          /*  case THREE_FRAGMENT:
                getOrderInfos(muserId, "", "", "1,3,4", "");
                break;
            case FOUR_FRAGMENT:
                getOrderInfos(muserId, "", "", "", "1");
                break;*/
        }
    }

    public void getOrderInfos(String userId, String beginDate, String endDate, String orderStatuss, String accessStatus) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", mToken);
        lRequest.addParam("userId", userId);
        lRequest.addParam("beginDate", beginDate);
        lRequest.addParam("endDate", endDate);
        lRequest.addParam("orderStatuss", orderStatuss);
        lRequest.addParam("accessStatus", accessStatus);
        Log.d(TAG, "orderStatuss==" + orderStatuss + "accessStatus==" + accessStatus);
        lRequest.setUri(ServerPort.GET_ORDER_LIST);
        lRequest.setUriType(UrlsTools.FOOD_INFO);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                try {
                    if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing() == true) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    closeProgressa();
                    T.showAnimErrorToast(getActivity().getApplicationContext(),   "请求超时！");
                } catch (Exception E) {

                }
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null&&"0".equals(code)) {
                    if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing() == true) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    Log.d(TAG, "responseBeanFood==" + responseBean);
                    switch (mCurIndex) {
                        case FIRST_FRAGMENT:
                            setData(responseBean);
                            break;
                        case SECOND_FRAGMENT:
                            setData(responseBean);
                            break;
                        case THREE_FRAGMENT:
                            setData(responseBean);
                            break;
                        case FOUR_FRAGMENT:
                            setData(responseBean);
                            break;
                    }
                }else{
                    T.showAnimToast(getActivity().getApplicationContext(),"数据为空！");
                }
            }
        });
    }

    FoodOrderInfosBean foodOrderInfos = null;
    List<FoodOrderInfosBean.DataBean> foodOrderInfoList = new ArrayList<>();
    FoodOrderInfoHolder foodOrderInfo = null;

    public void setData(String responseBean) {
        Log.d(TAG, "lazyLoad=====" + responseBean);
        mHasLoadedOnce = true;
        closeProgressa();
//        if (foodOrderInfo!=null){
//            foodOrderInfoList.clear();
//            foodOrderInfo.notifyDataSetChanged();
//            Log.d(TAG,"OK========");
//        }
        try{
            foodOrderInfos = new Gson().fromJson(responseBean, FoodOrderInfosBean.class);
            if (foodOrderInfos != null) {
                foodOrderInfoList = foodOrderInfos.getData();
                if (foodOrderInfoList!=null){
                    foodOrderInfo = new FoodOrderInfoHolder(getActivity().getApplicationContext(), foodOrderInfoList);
                    foodOrderInfo.registBack(this);
                    fragmentListview.setAdapter(foodOrderInfo);
                    foodOrderInfo.notifyDataSetChanged();
                }
            }
        }catch (Exception e){
            Log.e(TAG,"EXCEPTION==="+e.getMessage());
        }

    }
    public void reqFxiOrderInfo(String orderStatuss, int orderId, String userId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", mToken);
        lRequest.addParam("userId", userId);
        lRequest.addParam("orderStatus", 5);
        lRequest.addParam("orderId", orderId);
        Log.d(TAG, "orderStatus==" + orderStatuss + "orderId==" + orderId);
        lRequest.setUri(ServerPort.UPDATE_ORDER_LIST);
        lRequest.setUriType(UrlsTools.FOOD_INFO);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                try {
                    closeProgressa();
                    T.showAnimErrorToast(getActivity().getApplicationContext(),  R.string.toast_str+"");
                } catch (Exception E) {

                }
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null) {
                    if ("0".equals(code)) {
                        refreshData();
                    } else {
                        ToastTool.showText(getActivity().getApplicationContext(), "订单操作失败！");
                    }
                }
            }
        });
    }

    public void closeProgressa() {
        try {
            closeProgress();
        } catch (Exception E) {

        }
    }

    @Override
    public void showProgress() {
        try {
            showProgress(LlhFoodOrderAllFragment.this.getActivity());
        } catch (Exception e) {

        }
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception e) {

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }

    @Override
    public int getLayoutView() {
        return R.layout.llh_fragment_listview;
    }

    @Override
    public void initView(View view) {

    }

    @Override
    public void doBases() {

    }


    @Override
    public void callBack() {

    }

    @Override
    public void refreshData() {
        onRefreshReq();
    }

    @Override
    public void deleteData(FoodOrderInfosBean.DataBean holderOnclickBea) {

    }

    @Override
    public void updateData(FoodOrderInfosBean.DataBean holderOnclickBea) {
        if (holderOnclickBea != null) {
            reqFxiOrderInfo(holderOnclickBea.getOrderStatus(), holderOnclickBea.getOrderId(), muserId);
        }
    }

    //去支付
    @Override
    public void reqData(FoodOrderInfosBean.DataBean holderOnclickBea) {
        Intent intent = new Intent(getActivity().getApplicationContext(), FoodOrderPayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("foodOrderData", holderOnclickBea);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void insertData(FoodOrderInfosBean.DataBean holderOnclickBea) {

    }
}
